﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Windows.Controls;
using System.Linq;

namespace NthDownload.Common.Validation.Rules
{
    public class UriValidationRule : ValidationRule
    {
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            if (value == null)
            {
                return new ValidationResult(false, "Invalid Uri.");
            }
            
            string uriString = value.ToString();

            try
            {
                List<string> supportedSchemas = new List<string>(SupportedSchemas.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(s => s.ToLower().Trim()));

                Uri uri = new Uri(uriString);
                if (!supportedSchemas.Contains("all") && !supportedSchemas.Contains(uri.Scheme.ToLower()))
                {
                    return new ValidationResult(false, "'" + uri.Scheme + "' scheme unsupported.");
                }
            }
            catch 
            {
                return new ValidationResult(false, "Invalid Uri.");
            }

            return new ValidationResult(true, null);            
        }

        public string SupportedSchemas { get; set; }
    }
}
